import React, {FC, useCallback, useEffect, useImperativeHandle, useMemo, useRef} from "react";
import * as echarts from "echarts";
import download from "downloadjs";


interface EchartsProps {
    event?: any,
    options: any,
    width?: any,
    height?: any,
    init?: any,
    imgOption?: any,
    imgName?: any
}

const init: any = {
    grid: {
        left: '1%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    legend: {},
}

const Echarts: FC<EchartsProps> = (props) => {

    let {width = '100%', height = 500} = props

    const echartsRef: any = useRef()
    let echartInit: any = null

    const loadOptions = () => {
        let {options} = props
        if(!echartInit) {
            echartInit = echarts.init(echartsRef.current);
        }
        echartInit.clear()
        echartInit.setOption({...init, ...options}, true)
    }

    const downImg = useCallback((imgName: any) => {
        let {imgOption = {}} = props;
        let img = echartInit.getDataURL({...{
            type: 'jpeg',
            pixelRatio: 2,
            backgroundColor: '#fff'
        }, ...imgOption});
        let name = imgName ? imgName : 'echarts'
        download(img, name);
    }, [])

    const resizeListener = useCallback(() => {
        if (echartInit) {
            echartInit.resize();
        }
    }, [])

    useEffect(() => {
        if(props.height || props.width) {
            resizeListener()
        }
    }, [props.height, props.width])

    useEffect(() => {
        if(props.options) {
            loadOptions()
        }
    }, [props.options])

    useEffect(() => {
        const observer = new ResizeObserver((entries: any) => {
            for (let entry of entries) {
                const newWidth = entry.contentRect.width;
                const newHeight = entry.contentRect.height;
                if(newWidth || newHeight) {
                    resizeListener()
                }
            }
        });
        const targetDiv: any = document.querySelector(".sf_core_echart_box");
        observer.observe(targetDiv);
        const {event} = props
        if (event) {
            for (let k in event) {
                echartInit.on(k, event[k]);
            }
        }
        return () => {
            observer.disconnect()
            echartInit.dispose()
        }
    }, [])

    useImperativeHandle(props.init, () => {
        return {
            downImg,
            echartInit: echarts.init(echartsRef.current)
        }
    }, [props.options])

    const renderEcharts = useMemo(() => {
        return (<div className="sf_core_echart_box" style={{width: width, height: height}} ref={echartsRef}></div>)
    }, [props.options, width, height])

    return (renderEcharts)
}


export default React.memo(Echarts);

